﻿
Public MustInherit Class MetisSortedEntityList(Of T As IMetisCommonEntity)
    Inherits System.ComponentModel.BindingList(Of T)

    Public MustOverride Sub Reload()

    Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As T)
        Dim newIndex As Integer = 0
        For Each ListItem As T In Me
            If ListItem.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase) Then
                Throw New Exceptions.DublicateNameException(ListItem.Name)
            End If
            If ListItem.CompareTo(item) < 0 Then newIndex += 1
        Next

        MyBase.InsertItem(newIndex, item)
    End Sub

    Protected Overrides Sub SetItem(ByVal index As Integer, ByVal item As T)
        Dim newIndex As Integer = 0
        For Each ListItem As T In Me
            If ListItem.Name.ToUpper < item.Name.ToUpper Then newIndex += 1
        Next
        If newIndex = index Then
            MyBase.SetItem(index, item)
        Else
            MyBase.RemoveAt(index)
            InsertItem(newIndex, item)
        End If
    End Sub


    Public Overridable Function Find(ByVal ID As Integer) As T
        For Each Item As T In Me
            If Item.ID = ID Then
                Return Item
            End If
        Next
    End Function

    Public Overridable Function Find(ByVal Name As String) As T
        For Each Item As T In Me
            If Item.Name.Equals(Name, StringComparison.OrdinalIgnoreCase) Then
                Return Item
            End If
        Next
    End Function

End Class

